package com.ssish.saas.eccs.service;

import java.util.HashMap;
import java.util.Map;

import com.ssish.saas.eccs.mapper.SymUserMapper;
import com.ssish.saas.eccs.model.SymUser;
import com.ssish.saas.eccs.model.SymUserExample;
import com.ssish.saas.eccs.util.HttpClientUtil;
import com.ssish.saas.eccs.util.MD5Util;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class LoginService {
    @Autowired
    private SymUserMapper symUserMapper;

    @Value("${eccs.userAuth.url}")
    private String authUrl;

    /**
     * 判断登录信息是否合法
     * @param symUser
     * @param oldPassword
     * @return
     */
    public Boolean isValidUserInfo(SymUser symUser,String oldPassword){
        if(StringUtils.isBlank(symUser.getPasswd())){
            return Boolean.FALSE;
        }

        //调登录接口
        String enCryPassword = getEncryPassWord(oldPassword);
        System.out.println("加密的密码=========="+enCryPassword);
        if(StringUtils.equals(symUser.getPasswd(),enCryPassword)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    public SymUser getSymUserInfoById(String userName){
        return symUserMapper.selectByPrimaryKey(userName);
    }

    public int changePassWord(SymUser user){
   	 return symUserMapper.updateByPrimaryKeySelective(user);
   }
   
    public SymUser getSymUser(@Param("userid") String userid,@Param("password") String password){
	   	Map<String,String> map=new HashMap<String,String>();
	   	String enPassWord = MD5Util.MD5Encode(password,"UTF-8");
	   	map.put("userid", userid);
	   	map.put("password", enPassWord);
	   	return symUserMapper.getSymUser(map);
    }

    /**
     * 获取加密password
     * @param password
     * @return
     */
    public String getEncryPassWord(String password){
        //入参
        String paramData= "pstPassword="+password;
        //post请求
        try {
            String responseXml = HttpClientUtil.sendUserPost(authUrl,paramData);
            Document doc = DocumentHelper.parseText(responseXml);
            String value = doc.getRootElement().getText();
            return value;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }
}
